package com.ajz.sendsms.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.ajz.common.constants.Constants;
import com.ajz.sendsms.model.SendSmsRequest;
import com.ajz.sendsms.model.SendSmsResponse;
import com.ajz.sendsms.service.AliyunService;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * 
 * <p> </p>
 *
 * @author xyj
 * @date 2018年11月7日
 */
@Service
public class AliyunServiceImpl implements AliyunService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());


	private IAcsClient acsClient;

	//产品名称:云通信短信API产品,开发者无需替换
	private	static final String product = "Dysmsapi";
	//产品域名,开发者无需替换
	private static final String domain = "dysmsapi.aliyuncs.com";

	public AliyunServiceImpl() throws ClientException {
		//可自助调整超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		//初始化短信acsClient,暂不支持region化
		IClientProfile profile1 = DefaultProfile.getProfile
				("cn-hangzhou", Constants.ALIYUN_ACCESSKEYID, Constants.ALIYUN_ACCESSKEYSECRET);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		acsClient = new DefaultAcsClient(profile1);
	}


	
	@Async("taskExecutor")
	@Override
	public void sendVerificationCode(String mobile, String code) throws Exception{
		try {
			SendSmsRequest request = new SendSmsRequest();
			//组装请求对象-具体描述见控制台-文档部分内容
			SendSmsRequest sr = getSendSmsRequest(request,mobile);
			//必填:短信模板-可在短信控制台中找到
			sr.setTemplateCode(Constants.ALIYUN_CODE_TEMPLATE);
			//可选:模板中的变量替换JSON串,如模板内容为"您的验证码为${code}"时,此处的值为
			sr.setTemplateParam("{\"code\":\""+ code +"\"}");
			//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//			request.setOutId("yourOutId");
			//hint 此处可能会抛出异常，注意catch
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(sr);
			logger.info(">>>>>>>>>>>>>>>the response ["+ JSONObject.toJSON(sendSmsResponse) +"]");
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("手机号:" + mobile + "信息发送异常>>>>{}", e.getMessage());
			throw new Exception("手机号:" + mobile + "信息发送异常");
		}
	}

	private SendSmsRequest getSendSmsRequest(SendSmsRequest request, String mobile){
		//使用post提交
		request.setMethod(MethodType.POST);
		//必填:待发送手机号
		request.setPhoneNumbers(mobile);
		//必填:短信签名-可在短信控制台中找到
		request.setSignName(Constants.ALIYUN_SIGNNAME);
		return request;
	}
}
